package com.example.DownloadImageHelper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by PNB on 3/28/14.
 */
public class NotifyAdapter extends BaseAdapter {
    Context context;
    ArrayList<String> urls;
    ImageView imageView;
    ProgressBar progressBar;
    File folder;

    public NotifyAdapter(Context context, ArrayList<String> urls){
        this.context = context;
        this.urls = urls;
        folder = new File(Environment.getExternalStorageDirectory(),Environment.DIRECTORY_PICTURES);
    }

    @Override
    public int getCount() {
        return urls.size();
    }

    @Override
    public Object getItem(int i) {
        return urls.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.item,viewGroup,false);

        imageView = (ImageView)view.findViewById(R.id.imageView);
        progressBar = (ProgressBar)view.findViewById(R.id.progressBar);

        String url = urls.get(i);
        int pos = url.lastIndexOf("/");
        String name = url.substring(pos+1);
        File file = new File(folder,name);

        if(folder.exists()){
            try{
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                if(bitmap!=null){
                    imageView.setImageBitmap(bitmap);
                    progressBar.setVisibility(View.GONE);
                }
            }
            catch (Exception e){
                Log.i("Download Image", "Download Image Error");
            }
        }

        return view;
    }
}
